package com.epfuse.cloud.gateway.handler;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FastByteArrayOutputStream;
import cn.hutool.core.util.IdUtil;
import com.epfuse.cloud.common.core.constant.CacheConstants;
import com.epfuse.cloud.common.core.constant.SecurityConstants;
import com.epfuse.cloud.common.core.util.R;
import com.pig4cloud.captcha.ArithmeticCaptcha;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.cloud.commons.util.IdUtils;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.lang.NonNull;
import org.springframework.lang.NonNullApi;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * 验证码生成逻辑处理类
 */
@Slf4j
@RequiredArgsConstructor
public class ImageCodeHandler implements HandlerFunction<ServerResponse> {

    private static final Integer DEFAULT_IMAGE_WIDTH = 100;

    private static final Integer DEFAULT_IMAGE_HEIGHT = 40;

    private final RedisTemplate<String, Object> redisTemplate;

    @Override
    public Mono<ServerResponse> handle( ServerRequest serverRequest) {
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(DEFAULT_IMAGE_WIDTH, DEFAULT_IMAGE_HEIGHT);

        String result = captcha.text();

        // 保存验证码信息
        //Optional<String> randomStr = serverRequest.queryParam("randomStr");
        // 保存验证码信息
        String simpleUUID = IdUtil.fastSimpleUUID();

        redisTemplate.setKeySerializer(new StringRedisSerializer());

        redisTemplate.opsForValue().set(CacheConstants.DEFAULT_CODE_KEY + simpleUUID, result,
                SecurityConstants.CODE_TIME, TimeUnit.SECONDS);

        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        captcha.out(os);
        Map<String, Object> map = new HashMap<>();
        map.put("uuid", simpleUUID);
        map.put("img", Base64.encode(os.toByteArray()));
        // 默认开启
        map.put("captchaOnOff",true);
        ;
//
//        return ServerResponse.status(HttpStatus.OK).contentType(MediaType.IMAGE_JPEG)
//                .body(BodyInserters.fromResource(new ByteArrayResource(os.toByteArray())));
        return ServerResponse.status(HttpStatus.OK).body(BodyInserters.fromValue(R.ok(map)));
    }

}